package com.datastructure.test.findfirstindexinarray;

import java.util.ArrayList;

public class FindFirstIndexInArray {

    public static void main(String[] args) {
        FindFirstIndexInArray findFirstIndexInArray = new FindFirstIndexInArray();
        int[] data = {-2,1,2};
        int search = findFirstIndexInArray.search(data, -2);
        System.out.println(search);
    }

    public int search (int[] nums, int target) {
        // write code here
        return searchInArray(nums,target,0,nums.length-1);
    }

    private int searchInArray(int[] nums, int target, int start, int end) {
        if(start>end){
            return -1;
        }
        int mid = (start+end)/2;
        int midValue = nums[mid];
        if(midValue>target){
           return searchInArray(nums,target,start,mid-1);
        } else if(midValue<target){
           return searchInArray(nums,target,mid+1,end);
        } else {
            int temp = mid;
            while (temp-1>=0&&nums[temp-1]==target){
                temp--;
            }
            return temp;
        }
    }
}
